package com.example.springboot.service;

import com.example.springboot.entity.SysMenu;
import com.example.springboot.entity.SysMenuExample;
import com.example.springboot.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: jyf2000jyf
 * @Date: 2022/5/9
 * @Time: 23:01
 * @Email: 904593011@qq.com
 * @Description:
 **/
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    SysMenuMapper menuMapper;

    public Integer save(SysMenu menu) {
        if (menu.getId() == null) {  // user没有id，则表示是新增
            return menuMapper.insertSelective(menu);
        } else { // 否则为更新
            return menuMapper.updateByPrimaryKeySelective(menu);
        }
    }

    @Override
    public List<SysMenu> findAll() {
        SysMenuExample example = new SysMenuExample();
        example.createCriteria().andPidIsNull();
        List<SysMenu> sysMenus = menuMapper.selectByExample(example);
        for (SysMenu sysMenu : sysMenus) {
            SysMenuExample example1 = new SysMenuExample();
            example1.createCriteria().andPidEqualTo(sysMenu.getId());
            sysMenu.setChildren(menuMapper.selectByExample(example1));
        }
        return sysMenus;
    }

    @Override
    public Integer delete(Integer id) {
        return menuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<SysMenu> findAll(Integer pageNum, Integer pageSize, String name) {
        SysMenuExample example = new SysMenuExample();
        SysMenuExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc limit " + pageNum + "," + pageSize);
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        return menuMapper.selectByExample(example);
    }

    @Override
    public Integer getAmount(String name) {
        SysMenuExample example = new SysMenuExample();
        SysMenuExample.Criteria criteria = example.createCriteria();
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        return (Integer) (int) menuMapper.countByExample(example);
    }
}
